import App, { Container } from 'next/app';
import Link from 'next/link';
import { Layout, Menu, Icon, Avatar, Spin} from 'antd';
import 'antd/dist/antd.css';
import { withRouter } from 'next/router';
const { Header, Footer } = Layout;
import createStore from '../store';
import * as TYEPS from '../store/action-types'
const __REDUX_STORE__ = '__REDUX_STORE__';
import axios from '../utils/axios';
import {Provider} from 'react-redux'
import router from 'next/router';


function getStore(initialState) {
  if(typeof window === 'undefined') {
    // 如果是在服务器端运行的。 那么直接创建新仓库返回
    return createStore(initialState);
  } else { // 如果此代码是在客户端执行的,第一次会创建, 以后每次都复用上一次创建的
    if (!window[__REDUX_STORE__]) {
      window[__REDUX_STORE__] = createStore(initialState)
    }
    return window[__REDUX_STORE__]
  }
}

/*
全局布局组件
*/
class LayoutApp extends App<any> {
  store:any;
  routeChangeStart: any;
  routeChangeComplete: any;
  state = {
    loading: false
  };

  //↓此构造函数只会在客户端执行一次
  constructor(props){
    super(props);
    console.log('LayoutApp constructor received props:'/*,props*/)
    // console.log('props:',props);
    this.store = getStore(props.initialState);
  }

  static async getInitialProps(params){
    const {Component, ctx} = params;
    console.log('1.LayoutApp.getInitialProps'/*, params*/);
    const store = getStore({});
    let currentUser;
    const options = {
      url: '/api/currentUser'
      ,headers:{
        cookie:''
      }
    };
    //如果此方法是在服务器执行, 那么会有ctx.req属性, 它代表本次node请求对象
    if(ctx.req && ctx.req.headers.cookie){
      options.headers.cookie = ctx.req.headers.cookie; // cookie会作为是否登录过的依据
    }
    const response = await axios(options);
    if(response.data.code === 0){ // 说明用户已经登录过了
      currentUser = response.data.data;
      store.dispatch({type:TYEPS.SET_USER_INFO, payload: currentUser})
    }

    let pageProps = {};
    if(Component.getInitialProps){
      pageProps = await Component.getInitialProps(ctx);
    }

    return {pageProps,currentUser,initialState:store.getState()};
    //↑↑ 以上返回的对象会作为下面↓↓render函数的this.props
    //注意: 如果是服务端渲染, 那么这里↑↑的数据 会进行序列化(So↑↑返回的对象里最好只放可序列化的对象,不能放date啊请求对象啊什么的,只能放普通对象) 被嵌入html中
    //      当浏览器加载LayoutApp组件时 会将序列化的数据进行还原 并作为new LayoutApp时的参数传入
  }

  componentDidMount(){
    this.routeChangeStart = url => {
      this.setState({loading: true});
    };

    this.routeChangeComplete = url => {
      this.setState({loading: false})
    };

    router.events.on('routeChangeStart', this.routeChangeStart)
    router.events.on('routeChangeComplete', this.routeChangeComplete)
  }

  componentWillUnmount(){
    router.events.off('routeChangeStart', this.routeChangeStart)
    router.events.off('routeChangeComplete', this.routeChangeComplete)
  }

  render() {
    console.log('3.LayoutApp.render'/*, this.props*/);
    //Component就是页面组件
    let { Component } = this.props as any;
    let pathname = this.props.router.pathname;
    pathname = '/' + (pathname.split('/')[1]);
    return (
      <Provider store={this.store}>
        <style jsx>
          {`a{display:inline-block!important;}`}
        </style>
        <Layout>
          <Header className="header">
            <img src="/images/avatar.jpg" style={{ height: 31, margin: '16px 24px 16px 0px', float: 'left' }} />
            <Menu theme="dark" mode="horizontal" style={{ lineHeight: '64px', display: 'inline-block' }}
                  selectedKeys={[pathname]}
                  defaultSelectedKeys={[pathname]}>
              <Menu.Item key="/">
                <Icon type="home" /><Link href="/"><a>首页</a></Link>
              </Menu.Item>
              <Menu.Item key="/user">
                <Icon type="/user" /> <Link href="/user" ><a>用户管理</a></Link>
              </Menu.Item>
              <Menu.Item key="/profile">
                <Icon type="profile" /><Link href="/profile"><a>个人中心</a></Link>
              </Menu.Item>
              <Menu.Item key="/login">
                <Icon type="login" /><Link href="/login"><a>登录</a></Link>
              </Menu.Item>
            </Menu>
            {
              this.props.currentUser && (
                <div style={{display:'inline-block',float:'right',color:'red'}}>
                  <Avatar style={{color:'#F00',backgroundColor:'#ccc'}}>{this.props.currentUser.username}</Avatar>
                </div>
              )
            }
          </Header>
          {
            this.state.loading? <Spin style={{fontSize:50,margin:'50px auto'}}/>:<Component {...this.props.pageProps}/>
          }
          <Footer style={{ textAlign: 'center' }} >@copyright ahhh</Footer>
        </Layout>
      </Provider>
    )
  }
}

export default withRouter(LayoutApp);
